<template>
  <div class="permission">
    <el-card>
      <div style="text-align: right">
        <el-button
          type="primary"
          @click="addEvent(1, '0')"
        >添加权限页面</el-button>
      </div>
      <el-table :data="list" row-key="id">
        <el-table-column label="菜单名称" prop="name" />
        <el-table-column label="权限标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作" width="500px">
          <template v-slot="{ row }">
            <div>
              <el-button
                v-if="row.type === 1"
                type="text"
                @click="addEvent(1, row.id)"
              >添加权限页面</el-button>
              <el-button
                v-if="row.type === 1"
                type="text"
                @click="addEvent(2, row.id)"
              >添加权限按钮</el-button>
              <el-button type="text" @click="edit(row)">修改权限点</el-button>
              <el-button type="text" @click="del(row.id)">删除权限点</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 新增组件 -->
    <Add ref="add" v-model="show" @getData="getData" />
  </div>
</template>

<script>
import { sysPermission, sysPermissionDelete } from '@/api/permission.js'
import Add from './components/add.vue'
export default {
  components: {
    Add
  },
  data() {
    return {
      show: false,
      list: [{}]
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysPermission()
      this.list = this.changeData(res.data, '0')
      console.log(this.list)
    },
    changeData(arr, pid) {
      return arr.filter((item) => {
        if (item.pid === pid) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    },
    // 新增点击
    addEvent(type, pid) {
      this.show = true
      this.$refs.add.mode = 'add'

      this.$refs.add.form.type = type
      this.$refs.add.form.pid = pid
    },
    // 删除
    del(id) {
      this.$confirm('您确认删除该数据吗', '提示')
        .then(async() => {
          await sysPermissionDelete(id)
          this.$message.success('删除成功')
          this.getData()
        })
        .catch(() => {})
    },
    // 编辑
    edit(row) {
      this.show = true
      this.$refs.add.mode = 'edit'
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 20px;
}
</style>
